import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
// import { animateRotation, stopRotation } from "../antimations/animations";
import { animateRotation, createFixedLiquidLevel, stopRotation, removeLiquidLevel, animateColordefaultrun } from "../antimations/animations";
import {  Visible,tds, scale, ADS,T3,T4,T7K,T10K } from "../indexZJ";

const model = new THREE.Group();
const manager = new THREE.LoadingManager();
const loader = new GLTFLoader(manager);

let group0: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let group1: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let group2: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let group3: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let tankObject2: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let light62: THREE.Object3D<THREE.Object3DEventMap> | undefined;
let mixer: THREE.AnimationMixer;

let textMeshes: THREE.Mesh[] = [];  // 存储多个文本 Mesh
let previousOrders: string[] = [];  // 存储多个文本的先前值

let lastrungroup1: number | null = null;


let lastRunState1: boolean | null = null;
// 加载模型
loader.load(
    "/3D/test/zjm.glb",
    (gltf) => {
        const scene = gltf.scene;
        model.add(scene);
        mixer = new THREE.AnimationMixer(scene);

        // 获取目标对象group052
        tankObject2 = scene.getObjectByName("OBJ1723");
        light62=scene.getObjectByName("Cylinder460");
        
        group0 = scene.getObjectByName("group050");
        group1 = scene.getObjectByName("Obj374");
        //ads
      //  console.log("AAAAAAAAAAAAAAAAAAAA"+ADS.ADS_SCALE1_REALWGHT);
        //ads
        textMeshes.push(createTextMesh(`Real Weight:${ADS.ADS_SCALE1_REALWGHT} Kg`, -1676, -50, 1365, 40,-Math.PI/2,Math.PI/2,Math.PI/2));
        textMeshes.push(createTextMesh(`Des:${ADS.IngreName} `, -1676, -65, 1365, 40,-Math.PI/2,Math.PI/2,Math.PI/2));
        textMeshes.push(createTextMesh(`Code:${ADS.IngreCode} `, -1676, -80, 1365, 40,-Math.PI/2,Math.PI/2,Math.PI/2));
        textMeshes.push(createTextMesh(`TankNo:${ADS.TankNo} `, -1676, -95, 1365, 40,-Math.PI/2,Math.PI/2,Math.PI/2));
        //tds
        textMeshes.push(createTextMesh(`premix_temp:${tds.tds_premix_temperature} ℃`, 350, 100, -500, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`motor_temp:${tds.tds_motor_temp} ℃`, 350, 100, -450, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`speed_set:${tds.tds_speed_set} RPM`, 350, 100, -400, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`time_set:${tds.tds_time_set} min`, 350, 100, -350, 40,-Math.PI/2,0,0));
        //scale
        textMeshes.push(createTextMesh(`${scale.scale_27} Kg`, 1550, -200, 1185, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_28} Kg`,1550, -200, 1400, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_29} Kg`, 1550, -200, 1615, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_30} Kg`,1550, -200, 1830, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_31} Kg`, 1550, -200, 2035, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_32} Kg`,1550, -200, 2250, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_33} Kg`, 1550, -200, 2465, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        textMeshes.push(createTextMesh(`${scale.scale_34} Kg`,1550, -200, 2680, 40,-Math.PI/2,-Math.PI/4,-Math.PI/2));
        //T3
        textMeshes.push(createTextMesh(`Current:${T3.T3_CurrentActualValue} A`, 370, 100, 270, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`AccRunTime:${T3.T3_AccRunTime} H`, 370, 100, 320, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`ErrorCode:${T3.T3_ConverterErrorCode}  `, 370, 100, 370, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`FaultCode:${T3.T3_ConverterFaultCode}`, 370, 100, 420, 40,-Math.PI/2,0,0));
        //T4
        textMeshes.push(createTextMesh(`Current:${T4.T4_CurrentActualValue} A`, 850, 100, 270, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`AccRunTime:${T4.T4_AccRunTime} H`, 850, 100, 320, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`ErrorCode:${T4.T4_ConverterErrorCode}`, 850, 100, 370, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`FaultCode:${T4.T4_ConverterFaultCode}`, 850, 100, 420, 40,-Math.PI/2,0,0));
        //T7K
        textMeshes.push(createTextMesh(`Current:${T7K.T7K_CurrentActualValue} A`, -1520, 100, 270, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`AccRunTime:${T7K.T7K_AccRunTime} H`, -1520, 100, 320, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`ErrorCode:${T7K.T7K_ConverterErrorCode}  `, -1520, 100, 370, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`FaultCode:${T7K.T7K_ConverterFaultCode}`, -1520, 100, 420, 40,-Math.PI/2,0,0));
        //T10K
        textMeshes.push(createTextMesh(`Current:${T10K.T10K_CurrentActualValue} A`, -1070, 100, 270, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`AccRunTime:${T10K.T10K_AccRunTime} H`, -1070, 100, 320, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`ErrorCode:${T10K.T10K_ConverterErrorCode}  `, -1070, 100, 370, 40,-Math.PI/2,0,0));
        textMeshes.push(createTextMesh(`FaultCode:${T10K.T10K_ConverterFaultCode}`, -1070, 100, 420, 40,-Math.PI/2,0,0));

        textMeshes.forEach((textMesh) => {
            model.add(textMesh);
        });

        updateObjectProperties();
        
    },
    (xhr) => {
        // console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
    },
    (error) => {
        console.error("An error occurred:", error);
    }
);



// 创建文字纹理
function createTextTexture(text: string, fontSize: number): THREE.CanvasTexture {
    const canvas = document.createElement("canvas");
    const context = canvas.getContext("2d");

    if (!context) {
        throw new Error("Failed to get 2D context");
    }

    canvas.width = 500;
    canvas.height = 40;
    // 绘制背景（可选）
    // context.fillStyle = "rgba(112, 103, 232, 0.62)";
    // context.fillRect(0, 0, 1000, 1000);

    // 绘制文字
    context.fillStyle = "rgb(0, 0, 0)";
    context.font = `${fontSize}px Arial`;  // 动态设置字体大小
    context.textAlign = "center";
    context.textBaseline = "middle";
    context.fillText(text, canvas.width / 2, canvas.height / 2);

    const texture = new THREE.CanvasTexture(canvas);
    texture.needsUpdate = true;

    return texture;
}

// 创建文本 Mesh，并根据订单号提取的字体大小来设置
function createTextMesh(text: string, x: number, y: number, z: number, fontSize: number, mathx: number, mathy: number, mathz: number): THREE.Mesh {
    const texture = createTextTexture(text, fontSize);

    const material = new THREE.MeshBasicMaterial({ map: texture, transparent: true });
    
    const geometry = new THREE.PlaneGeometry(520, 30);

    const textMesh = new THREE.Mesh(geometry, material);
    textMesh.position.set(x, y, z);  // 每个文本的坐标不同
    textMesh.rotation.x = mathx; 
    textMesh.rotation.y = mathy; 
    textMesh.rotation.z = mathz; 
    textMesh.renderOrder = 1;
    return textMesh;
}

// 更新文本 Mesh
function updateTextMesh(textMesh: THREE.Mesh, text: string, fontSize: number) {
    const texture = createTextTexture(text, fontSize);
    const material = textMesh.material as THREE.MeshBasicMaterial;
    material.map = texture;
    material.map.needsUpdate = true;
}

function updateObjectProperties() {
    
    
    if (group0) {
        group0.visible = Visible.LTK; // 直接绑定可见性
    }

    // if (tankObject2 && currentRunState1 !== lastRunState1) {
    //     lastRunState1 = currentRunState1;
    //     animateRotation(tankObject2, "x", currentRunState1);
    // }
    
    // 遍历所有的文本 Mesh 并更新它们的文本
    textMeshes.forEach((textMesh, index) => {
        const newText = getTextForIndex(index);
        
        if (textMesh && newText !== previousOrders[index]) {
            previousOrders[index] = newText;
             // 第一条字体大小为48，第二条为20
            if(index <=3){
                const fontSize = 16
                updateTextMesh(textMesh, newText, fontSize);
            }else if(index >=8&&index <=15){
                const fontSize = 14
                updateTextMesh(textMesh, newText, fontSize);
            }else{
                const fontSize = 40
                updateTextMesh(textMesh, newText, fontSize);
            }

            
        }
    });
    const rungroup1 = tds.tds_plc_status;
    // console.log("tds"+rungroup1)
    if (group1 && rungroup1 !== lastrungroup1) {
        lastrungroup1 = rungroup1;
        updateTankAnimation(group1, rungroup1);
    }

    requestAnimationFrame(updateObjectProperties);
}
function updateTankAnimation(tanks: any, runx: number) {
    const run = runx 
    const initialColor = { r: tanks.material.color.r, g: tanks.material.color.g, b: tanks.material.color.b };
    const targetColor = new THREE.Color(0xA4F938); // Target color (green)

    animateColordefaultrun(tanks, initialColor, targetColor, 1, run);
}

// 获取不同批号文本的内容
function getTextForIndex(index: number): string {
    switch (index) {
        case 0:
            return `Real Weight:${ADS.ADS_SCALE1_REALWGHT} Kg`;
        case 1:
            return `Des:${ADS.IngreName} `;
        case 2:
            return `Code:${ADS.IngreCode} `;
        case 3:
            return `TankNo:${ADS.TankNo} `;
        case 4:
            return `premix_temp:${tds.tds_premix_temperature} ℃`;
        case 5:
            return `motor_temp:${tds.tds_motor_temp} ℃`;
        case 6:
            return `speed_set:${tds.tds_speed_set} R/pm`;
        case 7:
            return `time_set:${tds.tds_time_set} min`;
        case 8:
            return `${scale.scale_27} Kg`;
        case 9:
            return `${scale.scale_28} Kg`;
        case 10:
            return `${scale.scale_29} Kg`;
        case 11:
            return `${scale.scale_30} Kg`;
        case 12:
            return `${scale.scale_31} Kg`;
        case 13:
            return `${scale.scale_32} Kg`;
        case 14:
            return `${scale.scale_33} Kg`;
        case 15:
            return `${scale.scale_34} Kg`;
        case 16:
            return `Current:${T3.T3_CurrentActualValue} A`;
        case 17:
            return `AccRunTime:${T3.T3_AccRunTime} H`;
        case 18:
            return `ErrorCode:${T3.T3_ConverterErrorCode}`;
        case 19:
            return `FaultCode:${T3.T3_ConverterFaultCode}`;
        case 20:
            return `Current:${T4.T4_CurrentActualValue} A`;
        case 21:
            return `AccRunTime:${T4.T4_AccRunTime} H`;
        case 22:
            return `ErrorCode:${T4.T4_ConverterErrorCode}`;
        case 23:
            return `FaultCode:${T4.T4_ConverterFaultCode}`;
        case 24:
            return `Current:${T7K.T7K_CurrentActualValue} A`;
        case 25:
            return `AccRunTime:${T7K.T7K_AccRunTime} H`;
        case 26:
            return `ErrorCode:${T7K.T7K_ConverterErrorCode}`;
        case 27:
            return `FaultCode:${T7K.T7K_ConverterFaultCode}`;
        case 28:
            return `Current:${T10K.T10K_CurrentActualValue} A`;
        case 29:
            return `AccRunTime:${T10K.T10K_AccRunTime} H`;
        case 30:
            return `ErrorCode:${T10K.T10K_ConverterErrorCode}`;
        case 31:
            return `FaultCode:${T10K.T10K_ConverterFaultCode}`;
        
        default:
            return "";
    }
}

export default model;